package com.haidechizi.doublecache.process;

import com.haidechizi.doublecache.annotation.DoubleCache;
import com.haidechizi.doublecache.constant.CacheConstant;
import com.haidechizi.doublecache.service.LocalCacheService;
import com.haidechizi.doublecache.service.RemoteCacheService;
import com.haidechizi.doublecache.utils.ElParser;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.PostConstruct;
import java.util.Map;
import java.util.TreeMap;

/**
 * 基类
 */
public abstract class BaseProcessService implements ProcessService {

    @Autowired
    protected LocalCacheService localCacheService;

    @Autowired
    protected RemoteCacheService remoteCacheService;

    @PostConstruct
    public void init() {
        ProcessHolder.addProcessService(name(), this);
    }

    @Override
    public void process(ProcessContext processContext) throws Throwable {
        cacheKey(processContext);
        doProcess(processContext);
    }

    /**
     * do
     *
     * @param processContext
     */
    protected abstract void doProcess(ProcessContext processContext) throws Throwable;

    protected void cacheKey(ProcessContext processContext) {
        //拼接解析springEl表达式的map
        String[] paramNames = processContext.getParameterNames();
        Object[] args = processContext.getArgs();
        Map<String, Object> treeMap = new TreeMap<>();
        for (int i = 0; i < paramNames.length; i++) {
            treeMap.put(paramNames[i], args[i]);
        }

        DoubleCache doubleCache = processContext.getDoubleCache();
        String paramKey = ElParser.parse(doubleCache.key(), treeMap);
        String cacheKey = doubleCache.cacheName() + CacheConstant.CACHE_SEPARATOR + paramKey;
        processContext.setCacheKey(cacheKey);
    }


    protected abstract String name();
}
